﻿using Microsoft.AspNet.SignalR.Client;
using Microsoft.AspNet.SignalR.Client.Hubs;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PrinterPrinting;
using ConsoleApplicationSignalR;
using System.Windows.Forms;

namespace ASOFT.PRINTER
{
    class Program
    {
        static ServerCommunicator server;
        private static string CLIENT_NAME = ServerCommunicator.CLIENT_NAME;
        static List<string> printers;

        static void Main(string[] args)
        {
            // Cho phép khởi động cùng windows
            Setting.EnableStartOnWindowsStart();

            startPrinter();
            StartInvisible();
        }

        /// <summary>
        /// Khởi động window ẩn
        /// </summary>
        static void StartInvisible()
        {
            Form1 f = new Form1();

            // Set the form to be invisible
            f.FormBorderStyle = FormBorderStyle.FixedToolWindow;
            f.ShowInTaskbar = false;
            f.StartPosition = FormStartPosition.Manual;
            f.Location = new System.Drawing.Point(-20000, -20000);
            f.Size = new System.Drawing.Size(1, 1);
            //

            Application.Run(f);
        }

        /// <summary>
        /// Bắt đầu kết nối với server
        /// </summary>
        static void startPrinter()
        {
            Debug.WriteLine("************************startPrinter");
            // Create new hub connection
            server = new ServerCommunicator("http://localhost:3227");
            IHubProxy printerHub = server.CreateHubProxy("PrinterHub");
            if (printerHub == null)
            {
                Debug.WriteLine("Cannot create hub proxy");
            }
            else
            {
                Debug.WriteLine("Created hub proxy");
                server.SetEventListennerOn("printDocument", recieveCommand);
                server.SetEventListennerOn("getPrinters", getPrinters);
                server.SetEventListennerOn("OnError", onError);
                server.SetEventListennerOn("OnSuccess", onSuccess);
                server.SetEventListennerOn("available", available);
                // Start the connection


                // After success starting
                // Console call the method notify in the "ChatHub"               
                printers = new PrinterController().getPrinterNames();

                // Hàm gọi hàm khi bắt đầu kết nối
                //  - Notify server
                // server.CallServerHubMethod("WinNotify", CLIENT_NAME, server.HubConnection.ConnectionId);
                // - Gửi danh sách máy in cho server
                server.CallServerHubMethod("RecievePrinterNames", CLIENT_NAME, printers);
            }
        }

        /// <summary>
        /// Hàm được server gọi để kiểm tra trạng thái của máy in có tên truyền vào
        /// </summary>
        /// <param name="a"></param>
        private static void available(object name)
        {
            Console.WriteLine(name);
            bool printerAvailable = (printers.Find(p => p.Equals(name as string)) != null);
            server.CallServerHubMethod("PrinterAvailable", printerAvailable, name);

        }

        private static void onError(object a)
        {
            Console.WriteLine(a);
        }

        private static void onSuccess(object a)
        {
            Console.WriteLine(a);
        }

        private static void getPrinters(object a)
        {
            List<string> printers = new PrinterController().getPrinterNames();
            server.CallServerHubMethod("RecievePrinterNames", CLIENT_NAME, printers);
        }

        private static void recieveCommand(object printerName)
        {
            Console.WriteLine(printerName + " is WORKING ");
            Console.WriteLine("\"I am printing a document\"");
            PrinterController pc = new PrinterController();
            try
            {
                pc.PrintReciept(printerName as string);
                server.CallServerHubMethod("PrintSuccess", CLIENT_NAME, printerName);
            }
            catch (Exception e)
            {
                server.CallServerHubMethod("PrintError", e.Message, printerName);
            }
        }
        static void startPrinter2()
        {
            //Console.Write("Enter your name: ");
            string Name = null;
            if (string.IsNullOrWhiteSpace(Name))
            {
                Name = "W";
            }
            // Create new hub connection
            HubConnection hubConnection = new HubConnection("http://localhost:11716");

            // Create a hub proxy, named "PrinterHub" - The name of a hub class on server
            IHubProxy printerHub = hubConnection.CreateHubProxy("PrinterHub");

            // Register a event handler 
            // when the server execute a method named "broadcastMessage"
            // with parameter (string, string)
            // Detail: Clients.All.printDocument(name, message);
            printerHub.On<string>("printDocument", (printerName) =>
            {
                Console.Write(printerName + ": ");
                //Console.WriteLine(message);
                Console.WriteLine("I am printing a document");
                PrinterController pc = new PrinterController();
                try
                {
                    //printerHub.Invoke("Send", hubConnection.ConnectionId, "Printed");
                    pc.PrintReciept(printerName);
                    printerHub.Invoke("PrintSuccess", CLIENT_NAME, printerName);

                }
                catch (Exception e)
                {
                    printerHub.Invoke("PrintError", CLIENT_NAME, printerName);
                }
            });

            // Start the connection
            hubConnection.Start().Wait();

            // After success starting
            // Console call the method notify in the "ChatHub"
            //Debug.WriteLine("Connection ID =  '" + hubConnection.ConnectionId + "'");
            List<string> printers;
            try
            {
                printers = new PrinterController().getPrinterNames();
            }
            catch
            {
                throw;
            }

            if (printers != null)
            {
                printerHub.Invoke("WinNotify", CLIENT_NAME, hubConnection.ConnectionId);
                printerHub.Invoke("RecievePrinterNames", CLIENT_NAME, printers);
            }
        }



        //static void startChat()
        //{
        //    Console.Write("Enter your name: ");
        //    string Name = Console.ReadLine();
        //    if (string.IsNullOrWhiteSpace(Name))
        //    {
        //        Name = "Console App";
        //    }
        //    // Create new hub connection
        //    HubConnection hubConnection = new HubConnection("http://localhost:11716");

        //    // Create a hub proxy, named "ChatHub" - The name of a hub class on server
        //    IHubProxy chat = hubConnection.CreateHubProxy("ChatHub");

        //    // Register a event handler 
        //    // when the server execute a method named "broadcastMessage"
        //    // with parameter (string, string)
        //    // Detail: Clients.All.broadcastMessage(name, message);
        //    chat.On<string, string>("broadcastMessage", (name, message) =>
        //    {
        //        Console.Write("\n" + name + ": ");
        //        Console.WriteLine(message);
        //        Console.Write(Name + ": ");
        //    });

        //    // Start the connection
        //    hubConnection.Start().Wait();

        //    // After success starting
        //    // Console call the method notify in the "ChatHub"
        //    //Debug.WriteLine("Connection ID =  '" + hubConnection.ConnectionId + "'");
        //    chat.Invoke("Notify", Name, hubConnection.ConnectionId);

        //    //Start the chitchat
        //    string msg = null;
        //    Console.Write(Name + ": ");
        //    while ((msg = Console.ReadLine()) != "exit")
        //    {
        //        chat.Invoke("Send", Name, msg).Wait();
        //        Console.Write(Name + ": ");
        //    } 
        //}
    }
}